use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use fluviox_shared::models::*;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
use crate::AppState;

#[derive(Debug, Deserialize)]
pub struct CreateTopicRequest {
    pub name: String,
    pub partitions: u32,
    pub replication_factor: u16,
    pub retention_time: Option<u64>,
    pub compression: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct TopicInfo {
    pub name: String,
    pub partitions: u32,
    pub replication_factor: u16,
    pub size_bytes: u64,
    pub record_count: u64,
}

pub async fn list_topics(
    State(state): State<Arc<AppState>>,
) -> Result<Json<Vec<TopicInfo>>, StatusCode> {
    match state.fluvio.list_topics().await {
        Ok(topic_names) => {
            let mut topics = Vec::new();

            for name in topic_names {
                // 获取主题详细信息
                if let Ok(Some(topic_spec)) = state.fluvio.get_topic_info(&name).await {
                    topics.push(TopicInfo {
                        name,
                        partitions: topic_spec.partitions(),
                        replication_factor: topic_spec.replication_factor(),
                        size_bytes: 1024000, // 模拟大小
                        record_count: 1000, // 模拟记录数
                    });
                }
            }

            Ok(Json(topics))
        }
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

pub async fn create_topic(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CreateTopicRequest>,
) -> Result<Json<Value>, StatusCode> {
    // 验证主题名称
    if !fluviox_shared::fluvio_manager::is_valid_topic_name(&request.name) {
        return Ok(Json(json!({
            "status": "error",
            "message": "主题名称无效，只能包含字母、数字、连字符和下划线"
        })));
    }

    let topic = FluvioTopic {
        name: request.name.clone(),
        partitions: request.partitions,
        replication_factor: request.replication_factor,
        retention_time: request.retention_time,
        compression: request.compression,
    };

    match state.fluvio.create_topic(&topic).await {
        Ok(_) => {
            tracing::info!("主题 '{}' 创建成功", request.name);
            Ok(Json(json!({
                "status": "success",
                "message": format!("主题 '{}' 创建成功", request.name),
                "topic": {
                    "name": request.name,
                    "partitions": request.partitions,
                    "replication_factor": request.replication_factor
                }
            })))
        }
        Err(e) => {
            tracing::error!("创建主题失败: {}", e);
            Ok(Json(json!({
                "status": "error",
                "message": format!("创建主题失败: {}", e)
            })))
        }
    }
}

pub async fn delete_topic(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<Value>, StatusCode> {
    match state.fluvio.delete_topic(&name).await {
        Ok(_) => {
            tracing::info!("主题 '{}' 删除成功", name);
            Ok(Json(json!({
                "status": "success",
                "message": format!("主题 '{}' 删除成功", name)
            })))
        }
        Err(e) => {
            tracing::error!("删除主题失败: {}", e);
            Ok(Json(json!({
                "status": "error",
                "message": format!("删除主题失败: {}", e)
            })))
        }
    }
}

pub async fn get_topic_records(
    State(_state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> Result<Json<Vec<DataRecord>>, StatusCode> {
    // TODO: 实现主题记录查询
    tracing::info!("查询主题记录: {}", name);
    
    let records = vec![
        DataRecord {
            id: uuid::Uuid::new_v4(),
            topic: name.clone(),
            partition: 0,
            offset: 100,
            timestamp: chrono::Utc::now(),
            data: json!({"user_id": 123, "action": "login"}),
            metadata: std::collections::HashMap::new(),
        }
    ];
    
    Ok(Json(records))
}
